package parkshop.pmcourse.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import parkshop.pmcourse.domain.OrderComment;
import parkshop.pmcourse.domain.Orderdetail;
import parkshop.pmcourse.domain.Orders;
import parkshop.pmcourse.domain.Product;
import parkshop.pmcourse.domain.Shop;
import parkshop.pmcourse.dto.PageBean;
import parkshop.pmcourse.dto.User;
import parkshop.pmcourse.mapping.OrderCommentMapper;
import parkshop.pmcourse.mapping.OrderdetailMapper;
import parkshop.pmcourse.mapping.OrdersMapper;
import parkshop.pmcourse.mapping.ProductMapper;
import parkshop.pmcourse.mapping.ShopMapper;
import parkshop.pmcourse.service.OrdersService;
import parkshop.pmcourse.utils.ConstantUtil;
import parkshop.pmcourse.utils.DateUtil;

@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private OrdersMapper orderMapper;
	
	@Autowired
	private OrderdetailMapper orderdetailMapper;
	
	@Autowired
	private ShopMapper shopMapper;
	@Autowired
	private ProductMapper productMapper;
	
	@Autowired
	private OrderCommentMapper orderCommentMapper;
	
	
	@Override
	public void saveOrder(Orders orders, List<Orderdetail> orderdetailList) {
		// TODO Auto-generated method stub
		
		orderMapper.insertSelective(orders);
		for (Orderdetail orderdetail : orderdetailList) {
			orderdetail.setOrderId(orders.getId());
			orderdetail.getProductId();
			orderdetailMapper.insertSelective(orderdetail);
		}
	}

	@Override
	public PageBean selectAllOrders(int pageNumber) {
		int count = orderMapper.selectOrdersCount();
		PageBean pageBean = new PageBean(pageNumber, 10, count);
		List<Orders> ordersList = orderMapper.selectAllOrders(pageBean);
		pageBean.setRecordList(ordersList);
		return pageBean;
	}

	@Override
	public PageBean selectAllOrdersByUser(int pageIndex, String userType, Long userId) {
		// TODO Auto-generated method stub
		int count=0;
		PageBean pageBean = new PageBean();
		pageBean.setStartindex((pageIndex-1)*ConstantUtil.pageSize);// pageIndex 从 0开始
		pageBean.setPageSize(ConstantUtil.pageSize);
		List<Orders> list=null;
		
		switch(userType){		
		case ConstantUtil.userTypeCustomer:
			pageBean.setId(userId);
			count=orderMapper.selectOrdersCountByCustomerId(userId);
			list=orderMapper.selectAllOrdersByCustomerId(pageBean);
			break;
		case ConstantUtil.userTypeShopOwner:
			Shop shop=shopMapper.selectByShopOwnerId(userId);
			pageBean.setId(shop.getId());
			count=orderMapper.selectOrdersCountByShopId(shop.getId());
			list=orderMapper.selectOrdersByShopId(pageBean);
			break;
		case ConstantUtil.userTypeAdministrator:
			count=orderMapper.selectOrdersCount();
			list=orderMapper.selectOrdersByAdministrator(pageBean);
			break;		
		}
		
		
		
		for(Integer i=0;i<list.size();++i){
			Orders order=list.get(i);
			Orderdetail detail=orderdetailMapper.selectByOrderId(order.getId());
			if(detail==null){
				--i;
				list.remove(order);
				continue;
			}
			Product product=productMapper.selectByPrimaryKey(detail.getProductId());
			if(product==null){
				--i;
				list.remove(order);
				continue;
			}
			order.setProductId(product.getId());
			order.setImageUrl(product.getImageUrl());
			order.setQuantity(detail.getQuantity());
			order.setProductName(product.getName());
		}
		pageBean.setRecordList(list);
		pageBean.setRecordCount(count);
		pageBean.setPageCount(count%ConstantUtil.pageSize==0?count/ConstantUtil.pageSize:count/ConstantUtil.pageSize+1);
		
		return pageBean;
	}

	
	
	@Override
	public Orders paying(Long orderId, User user) {
		// TODO Auto-generated method stub
         
         Orders order=orderMapper.selectByPrimaryKey(orderId);
		order.setOrderStatus(ConstantUtil.orderStatus_unshiped);
		order.setPayTime(new Date());
		orderMapper.updateByPrimaryKeySelective(order);
		return order;
	}
/*
	@Override
	public PageBean paying(Long[] orderId, User user) {
		 PageBean pageBean=selectAllOrdersByUser(1, user.getType(), user.getId());
         
			
			List<Orders> orderList=pageBean.getRecordList();
			if(orderList!=null&&orderList.size()>0){
				int size=orderList.size();
				for(int i=0;i<size;++i){
					orderList.get(i).setOrderStatus(ConstantUtil.orderStatus_unshiped);// 买家已付款，卖家未发货
					orderList.get(i).setPayTime(new Date());
					orderMapper.updateByPrimaryKeySelective(orderList.get(i));
				}
			}	
			return pageBean;
	}*/

	@Override
	public Orders deliver(Long orderId) {
		// TODO Auto-generated method stub
		Orders order=orderMapper.selectByPrimaryKey(orderId);
		order.setOrderStatus(ConstantUtil.orderStatus_unreceived);
		int rows=orderMapper.updateByPrimaryKeySelective(order);
		return rows==1?order:null;
	}

	@Override
	public Orders received(Long orderId) {
		
		Orders order=orderMapper.selectByPrimaryKey(orderId);
		order.setOrderStatus(ConstantUtil.orderStatus_unfinish);
		int rows=orderMapper.updateByPrimaryKeySelective(order);
		return rows==1?order:null;
	}

	@Override
	public Orders getOrderByOrderId(Long id) {
		// TODO Auto-generated method stub
		return orderMapper.selectByPrimaryKey(id);
	}


	@Override
	public float[] getIncomeByDate(int dateType, User user) {
		// TODO Auto-generated method stub
		Date date1=new Date();
		int a=0;
		date1=DateUtil.getIntervalDate(date1, dateType, -1);
		Map<Integer,List<Orders>> map=getDivideOrdersByDate(date1,dateType, user);
		float[]  incomes=new float[map.size()];
		boolean flag=ConstantUtil.userTypeAdministrator.equals(user.getType());
		for(Integer i=0;i<map.size();++i){
			List<Orders> list=map.get(i);
			for(Orders order:list)
				incomes[i]+=flag?order.getOrderMoney()*order.getCommissionRates():order.getOrderMoney();
		}
		
		return incomes;
	}
	@Override
	public float[] getIncomeBySpecialDate(Date date, int dateType, User user) {
		// TODO Auto-generated method stub
		// 如果 date 与当前系统时间不超过5分钟，则表示是用户选择了当前系统时间。需要将时间点向前位移一个单位
		Calendar calendar=Calendar.getInstance();
		calendar.add(Calendar.MINUTE,-5);
		int compare=date.compareTo(calendar.getTime());
		if(compare>0){
			date=DateUtil.getIntervalDate(date, dateType, -1);
		}
		
		Map<Integer,List<Orders>> map=getDivideOrdersByDate(date,dateType, user);
		float[]  incomes=new float[map.size()];
		boolean flag=ConstantUtil.userTypeAdministrator.equals(user.getType());
		for(Integer i=0;i<map.size();++i){
			List<Orders> list=map.get(i);
			for(Orders order:list)
				incomes[i]+=flag?order.getOrderMoney()*order.getCommissionRates():order.getOrderMoney();
		}
		
		return incomes;
	}
	private Map<Integer,List<Orders>> getDivideOrdersByDate(Date time1,int dateType, User user) {
		// TODO Auto-generated method stub
		Map<Integer,List<Orders>> map=new HashMap<Integer,List<Orders>>();
		
		// 默认为一天24小时
		
		int timeSpanType=Calendar.HOUR_OF_DAY;// 比 dateType小一个级别的日期
		int spansSum=24;
		switch(dateType){
		case Calendar.DAY_OF_YEAR:
			timeSpanType=Calendar.HOUR_OF_DAY;
			spansSum=24;
			break;
		case Calendar.WEEK_OF_YEAR:
			timeSpanType=Calendar.DAY_OF_YEAR;
			spansSum=7;
			break;
		case Calendar.MONTH:
			timeSpanType=Calendar.WEEK_OF_MONTH;
			spansSum=4;
			break;
		case Calendar.YEAR:
			timeSpanType=Calendar.MONTH;
			spansSum=12;
			break;
		default:
			return null;		
		}		
		Date timeLast=DateUtil.getIntervalDate(time1, timeSpanType, 1);
		
		for(int i=0;i<spansSum;++i){
			map.put(i,getOrdersByDates( time1, timeLast,ConstantUtil.orderStatus_unfinish,true, user));
			time1=timeLast;
			timeLast=DateUtil.getIntervalDate(time1, timeSpanType, 1);
		}
		
		return map;
	}
	

/*查询特定的订单，查询条件
 * time1 - timeNext 时间段的订单
 * status 订单状态
 *  isRangeStatus 特定状态的订单或者大于该状态的订单
 *  user 查询该用户的订单
 * 
 */
	private List<Orders> getOrdersByDates(Date time1,Date timeNext,int status,boolean isRangeStatus,User user){
		List<Orders> list=null;
		
		Long shopId=(long) ConstantUtil.adminShopMark;
		PageBean pageBean=new PageBean();
		pageBean.setTime(time1);
		pageBean.setTimeNext(timeNext);
		pageBean.setEndPageIndex(status);
		
		if(ConstantUtil.userTypeShopOwner.equals(user.getType())){
			shopId=shopMapper.selectByShopOwnerId(user.getId()).getId();
			pageBean.setId(shopId);
			list=isRangeStatus?orderMapper.selectAllByShopIdAndDateWithAboveRangeStatus(pageBean):orderMapper.selectAllByShopIdAndDateWithStatus(pageBean);
		}else if(ConstantUtil.userTypeAdministrator.equals(user.getType())){
			list=isRangeStatus?orderMapper.selectByAdministratorAndDateWithAboveRangeStatus(pageBean):orderMapper.selectByAdministratorAndDate(pageBean);
		}else if(ConstantUtil.userTypeCustomer.equals(user.getType())){
			pageBean.setId(user.getId());
			list=isRangeStatus?orderMapper.selectAllByCustomerIdAndDateWithAboveRangeStatus(pageBean):orderMapper.selectAllByCustomerIdAndDateWithStatus(pageBean);
		}
		return list;
	}

	@Override
	public Product getOrderProduct(Long orderId) {
		// TODO Auto-generated method stub
		Orderdetail orderDetail=orderdetailMapper.selectByOrderId(orderId);
		return productMapper.selectByPrimaryKey(orderDetail.getProductId());		
	}

	@Override
	public Orderdetail getOrderDetailByOrderId(Long id) {
		// TODO Auto-generated method stub
		return orderdetailMapper.selectByOrderId(id);
		
	}

	@Override
	public boolean saveOrderComment(OrderComment comment) {
		// TODO Auto-generated method stub
		int rows=orderCommentMapper.insertSelective(comment);
		
		return rows==1?true:false;
	}

	@Override
	public PageBean selectSpecificStatusOrdersByUser(int pageIndex, String userType, Long userId, int status) {
		// TODO Auto-generated method stub
		int count=0;
		PageBean pageBean = new PageBean();
		pageBean.setStartindex((pageIndex-1)*ConstantUtil.pageSize);// pageIndex 从 0开始
		pageBean.setPageSize(ConstantUtil.pageSize);//设置一页的大小
		pageBean.setEndPageIndex(status);// 借用 pageBean 的 beginPageIndex字段，用于传递 status
		pageBean.setId(userId);
/*		PageBean countBean=new PageBean();
		countBean.setId(userId);
		countBean.setEndPageIndex(status);*/
		List<Orders> list=null;
		
		switch(userType){		
		case ConstantUtil.userTypeCustomer:
			count=orderMapper.selectStatusOrdersCountByCustomerId(pageBean);
			list=orderMapper.selectStatusOrdersByCustomerId(pageBean);
			break;
		case ConstantUtil.userTypeShopOwner:
			Shop shop=shopMapper.selectByShopOwnerId(userId);
			pageBean.setId(shop.getId());
			count=orderMapper.selectStatusOrdersCountByShopId(pageBean);
			list=orderMapper.selectStatusOrdersByShopId(pageBean);
			break;
		case ConstantUtil.userTypeAdministrator:
			count=orderMapper.selectOrdersCount();
			list=orderMapper.selectOrdersByAdministrator(pageBean);
			break;		
		}
		
		
		list=addProductInfoIntoOrdersList(list);
		pageBean.setRecordList(list);
		pageBean.setRecordCount(count);
		pageBean.setCurrentPage(pageIndex);
		pageBean.setPageSize(ConstantUtil.pageSize);
		pageBean.setPageCount(count%ConstantUtil.pageSize==0?count/ConstantUtil.pageSize:count/ConstantUtil.pageSize+1);
		
		return pageBean;
	}

	@Override
	public PageBean getOrdersByDate(Date from, Date to, User user,int status) {
		// TODO Auto-generated method stub
		List<Orders> list=getOrdersByDates(from, to, status, false,user);
		if(list==null)
			return null;
		
		list=addProductInfoIntoOrdersList(list);
		PageBean pageBean=new PageBean();
		pageBean.setCurrentPage(1);
		pageBean.setRecordList(list);
		int count=list.size();
		pageBean.setRecordCount(count);
		pageBean.setPageCount(count%ConstantUtil.pageSize==0?count/ConstantUtil.pageSize:count/ConstantUtil.pageSize+1);
		
		
		return pageBean;
	}
	
	private List<Orders> addProductInfoIntoOrdersList(List<Orders> list){
		for(Integer i=0;i<list.size();++i){
			Orders order=list.get(i);
			Orderdetail detail=orderdetailMapper.selectByOrderId(order.getId());
			if(detail==null){
				--i;
				orderMapper.deleteByPrimaryKey(order.getId());
				list.remove(order);	
				continue;
			}
			Product product=productMapper.selectByPrimaryKey(detail.getProductId());
			if(product==null){
				--i;
				orderMapper.deleteByPrimaryKey(order.getId());
				list.remove(order);
				continue;
			}
			order.setProductId(product.getId());
			order.setImageUrl(product.getImageUrl());
			order.setQuantity(detail.getQuantity());
			order.setProductName(product.getName());
		}
		return list;
	}

	@Override
	public boolean deleteOrderById(Long orderId) {
		// TODO Auto-generated method stub
		int row=orderMapper.deleteByPrimaryKey(orderId);
		
		
		return row==1?true:false;
	}

	
	
}
